const puppeteer = require('puppeteer')

const url = 'https://movie.douban.com/tag/#/?sort=R&range=7,10&tags=%E7%94%B5%E5%BD%B1'

const sleep = (time) => new Promise(resolve => {
  console.log('sleep')
  setTimeout(resolve, time)
})
;(async () => {
  console.log('start visit the target page')

  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    dumpio: false
  })

  // 创建一个 新页面
  const page = await browser.newPage()
  await page.goto(url, {
    waitUntil: 'networkidle2'
  })

  await sleep(3000)
  await page.waitForSelector('.more')

  for(let i = 0; i < 1; i++) {
    await page.click('.more')
    await sleep(3000)
  }

  // 进入 页面的上下文环境
  const result = await page.evaluate(() => {
    // 浏览器 环境
    var $ = window.$
    var items = $('.list-wp a')
    var links = []

    if (items.length >= 1) {
      items.each((index, item) => {
        var it = $(item)

        var doubanId = it.find('div').data('id')
        var title = it.find('.title').text()
        var rate = Number(it.find('.rate').text())
        var poster = it.find('img').attr('src').replace('s_ratio', 'l_ratio')

        // https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2175329193.jpg
        // https://img3.doubanio.com/view/photo/l_ratio_poster/public/p2175329193.jpg
        
        links .push({
          doubanId,
          title,
          rate,
          poster
        })
        
      })

      return links
    }
  })

  process.send({result})
  process.exit(0)
  // 关闭任务
  browser.close()
})()